<?php


namespace App\Http\Controllers\App;


use App\Exceptions\BasicException;
use App\Http\Controllers\BaseController;
use App\Repositories\Activity\Pirate2022\PirateRepository;
use App\Repositories\Lottery\SettingRepository;
use App\Repositories\Lottery\UserRepository;
use App\Resource\User\BalanceResource;
use App\Response\Response;
use App\Services\Draw\DrawManager;
use Illuminate\Http\Request;
use App\Resource\Setting\Resource as SettingResource;

class LotteryFantasyController extends BaseController
{
    protected $drawType = 'fantasy';

    public function balance(Request $request)
    {
        $userId  = (int)UID;
        $balance = UserRepository::getInstance()->info($userId);
        $model   = BalanceResource::make($balance);
        return Response::sendData($model);
    }

    public function levels(Request $request)
    {
        $levelList = (new DrawManager($this->drawType))->getLevelList();
        return Response::sendData($levelList);
    }

    public function user(Request $request)
    {
        $userId       = (int)UID;
        $userDrawInfo = (new DrawManager($this->drawType))->getUserDrawInfo($userId);
        $userDrawInfo->monster_hp = app('repo_add_pool_fantasy')->getMonsterHp($userId);
        return Response::sendData($userDrawInfo);
    }

    public function illustration(Request $request)
    {
        $poolConfig                = (new DrawManager($this->drawType))->getPoolConfig();
        $illustration['help_info'] = $poolConfig['help_info'];

        return Response::sendData($illustration);
    }


    public function setting(Request $request)
    {
        $setting = SettingRepository::getInstance()->one([]);
        $model   = SettingResource::make($setting);
        return Response::sendData($model);
    }

    public function rank(Request $request)
    {
        $userId       = (int)UID;
        $type         = $request->input('type');
        $limit        = (int)$request->query('per_page', 10);
        $rankListData = (new DrawManager($this->drawType))->getRankList($userId, $type, $limit);

        $rankUserIds        = array_keys($rankListData['rank_list']);
        $rankUserIds[]      = $userId;
        $userInfoList       = app('repo_user_data')->batchGetUserInfoByIds($rankUserIds, ['user_id', 'nickname', 'head_picture']);
        $userInfoListWithId = $userInfoList->KeyBy('user_id');
        $rankRes            = [];

        $rankRes['user_rank'] = ['user_id' => $userId, 'nickname' => $userInfoListWithId[$userId]['nickname'], 'head_picture' => $userInfoListWithId[$userId]['head_picture'], "diff" => null,
                                 'index'   => ($rankListData['user_rank']['rank'] !== null) ? ($rankListData['user_rank']['rank'] + 1) : 0, 'score' => $rankListData['user_rank']['score'] ?? 0];

        $index         = 1;
        $lastRankScore = 0;
        foreach ($rankListData['rank_list'] as $key => $rankScore) {
            $rankRes['rank_list'][] = ['user_id' => $key, 'nickname' => $userInfoListWithId[$key]['nickname'], 'head_picture' => $userInfoListWithId[$key]['head_picture'],
                                       'index'   => $index, 'diff' => ($lastRankScore - $rankScore) < 0 ? 0 : ($lastRankScore - $rankScore), 'score' => $rankScore];

            if ($key == $userId) {
                $rankRes['user_rank']['diff']  = ($lastRankScore - $rankListData['user_rank']['score']) < 0 ? 0 : ($lastRankScore - $rankListData['user_rank']['score']);
                $rankRes['user_rank']['index'] = $index;
            }
            $lastRankScore = $rankScore;
            $index++;
        }
        if ($rankRes['user_rank']['diff'] === null) {
            $rankRes['user_rank']['diff'] = $lastRankScore - $rankListData['user_rank']['score'];
        }
        return Response::sendData($rankRes);
    }

    public function prizes(Request $request)
    {
        $prizeRes                        = [];
        $drawManager                     = (new DrawManager($this->drawType));
        $prizeList                       = $drawManager->getAllPrizeList();
        $prizeRes['gift_list']           = $prizeList;
        $prizeRes['plutocrat_list']      = $drawManager->getAllPlutocratList();
        return Response::sendData($prizeRes);
    }

    public function swap(Request $request)
    {
        $userId = (int)UID;
        $count  = intval($request->input('count'));
        if ($count <= 0) {
            throw new BasicException(-1, '非法请求');
        }
        (new DrawManager($this->drawType))->swapBalance($userId, $count);
        return Response::sendData([]);
    }

    public function draw(Request $request)
    {
        $userId = (int)UID;
        $count  = (int)($request->input('count'));
        $config_count_arr =  explode(',',app('model_config')->getValue(strtoupper($this->drawType).'_DRAW_INFO') ?? '1,10,100');
        if ($count <= 0 || !in_array($count, $config_count_arr)) {
            throw new BasicException(-1, '非法请求');
        }
        $giftListRes = [];
        $totalCoin   = 0;
        // $draw = LotteryRepository::getInstance()->draw($userId, $count);
        $drawData = (new DrawManager($this->drawType))->draw($userId, $count);
        if (!empty($drawData['critical_gift'])) {
            $giftListRes[] = [
                'id'                    => $drawData['critical_gift']['id'],
                'name'                  => $drawData['critical_gift']['name'],
                'picture'               => $drawData['critical_gift']['picture'],
                'critical_gift_level'   => $drawData['critical_gift']['level'],
                'count'                 => $drawData['critical_gift']['count'],
                'price'                 => $drawData['critical_gift']['price'],
                "gift_mark_name"        => $drawData['critical_gift']['level_name']
            ];
            $totalCoin  += $drawData['critical_gift']['price'];
        }
        $data = $this->forDrawGift($drawData, $totalCoin);
        $totalCoin = $data['totalCoin'];
        $is_show_price = $data['is_show_price'];
        $is_show_animation = $data['is_show_animation'];
        $drawData = $data['drawData'];
        $giftListRes = array_merge($giftListRes, $drawData['gift_list']);
        /*try {
            PirateRepository::getInstance()->addExchangeCount($userId, $giftListRes);
        } catch (BasicException $e) {
            if ($e->getCode() != 600001) {
                throw $e;
            }
        }*/
        $giftListRes = app('repo_add_pool_fantasy')->getMonsterDisplay($giftListRes, UID);

        $drawRes = ["gift_list" => $giftListRes, 'total_coin' => $totalCoin, 'is_show_price' => $is_show_price, 'is_show_animation' => $is_show_animation,
            'monster_hp' => app('repo_add_pool_fantasy')->getMonsterHp($userId), 'display_level' => $giftListRes[0]['display_level']];
//        $draw = LotteryRebuildRepository::getInstance()->draw($userId, $count);
//        $models = DrawRecordRepository::getInstance()->get(['draw_id' => $draw->id])->sortByDesc('prize_price');
        return Response::sendData($drawRes);
    }

    public function clearIOputCache(Request $request)
    {
//        $userId = (int)($request->input('user_id'));
//        $poolId = (int)($request->input('pool_id'));
//        app('redis')->del(CacheKey::USER_DATE_PUT_RECORD . ":$userId" . "_" . date("Y-m-d"));
//        app('redis')->del(CacheKey::USER_WEEK_PUT_RECORD . ":$userId" . "_" . date("Y-W"));
//        app('redis')->del(CacheKey::POOL_DATE_PUT_RECORD . ":$poolId" . "_" . date("Y-m-d"));
//        app('redis')->del(CacheKey::POOL_WEEK_PUT_RECORD . ":$poolId" . "_" . date("Y-W"));
//        app('redis')->del(CacheKey::POOL_ROUND . ":$poolId");
//        app('redis')->del(CacheKey::USER_LAST_BIG_DRAW_COUNT);

        /*$keys = app('redis')->keys("fantasy:*");
        foreach ($keys as $key) {
            app('redis')->del($key);
        }*/
    }

    public function setAuto(Request $request)
    {
        $userId = (int)UID;
        $is_auto  = intval($request->input('is_auto'));
        if (!in_array($is_auto, [1, 0])) {
            throw new BasicException(-1, '非法请求');
        }
        (new DrawManager($this->drawType))->setAuto($userId, $is_auto);
        return Response::sendData([], '成功');
    }
}
